package cn.hotel.dao;

import cn.hotel.utlis.Crud;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class LogDao extends Crud implements Log {
    @Override
    public List<cn.hotel.pojo.Log> logList(String operator, int atPresent, int sum) {
        String sql = "select * from log ";
        StringBuffer sbf = new StringBuffer(sql);
        List<Object> data = new ArrayList<>();
        if(operator != null){
            sbf.append(" where operator = ?");
            data.add(operator);
        }
        sbf.append(" ORDER BY operationTime DESC LIMIT ?,?");
        data.add(atPresent);
        data.add(sum);
        ResultSet resultSet = getResultSet(sbf.toString(),data);
        List<cn.hotel.pojo.Log> logs = new ArrayList<>();
        cn.hotel.pojo.Log log = null;
        try {
            while (resultSet.next()){
                log = new cn.hotel.pojo.Log();
                log.setId(resultSet.getLong(1));
                log.setOperator(resultSet.getString(2));
                log.setOperationTime(resultSet.getString(3));
                log.setOperatorContent(resultSet.getString(4));
                logs.add(log);
            }
            return logs;
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            this.setClear(resultSet);
        }
        return logs;
    }

    @Override
    public int elaboration(String operator) {
        String sql = "SELECT COUNT(1) FROM LOG ";
        StringBuffer sbf = new StringBuffer(sql);
        List<Object> data = new ArrayList<>();
        if(operator != null){
            sbf.append(" WHERE OPERATOR = ? ");
            data.add(operator);
        }
        ResultSet resultSet = getResultSet(sbf.toString(),data);
        int num = -1;
        try {
            while (resultSet.next()){
                num = resultSet.getInt(1);
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            this.setClear(resultSet);
        }
        return num;
    }

    @Override
    public int addLog(String operator, String content) {
        String sql = "INSERT INTO `log`(`operator`,`operationTime`,`operatorContent`) VALUES (?,NOW(),?)";
        List<Object> data = new ArrayList<>();
        data.add(operator);
        data.add(content);
        return getInt(sql,data);
    }

    @Override
    public int deleteLog(String operator) {
        String sql = "DELETE FROM `log` WHERE operator = ?";
        List<Object> data = new ArrayList<>();
        data.add(operator);
        return getInt(sql,data);
    }
}
